<template>
<div class="clearfix">
  <div class="pull-left width70 border padding10">
    <div>
      <label>当前分类：</label>
      <span>{{ surveyData.categorys[selectCategoryIndex.parentIndex].name }} -> {{ selectCategory.name }}</span>
    </div>
    <hr/>
    <div class="questionsBox">
      <div id="questionsBox">
        <!-- div class="bottom10" v-for="(questionData, index) in selectCategory.questions" -->
        <div class="bottom10" v-for="(questionData, index) in showQuestions">
          <questionsComp :questionIndex="index + pageSize * (page - 1)" :question="questionData" 
          @answerQuestion="answerQuestion"
          @answerQuestionOther="answerQuestionOther"></questionsComp>
          <hr/>
        </div>
      </div>
      <div class="text-center margin">
        <button class="btn btn-default" v-if="page > 1" v-on:click="handleCurrentChange(page - 1)">上一页</button>
        <span style="margin-left: 60px;"></span>
        <button class="btn btn-custom" v-if="page <= (selectCategory.questions.length / pageSize) " v-on:click="handleCurrentChange(page + 1)">下一页</button>
      </div>
      <div style="margin-top: 30px;"></div>
      <el-pagination v-if="selectCategory.questions.length>0"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-size="pageSize"
      layout="prev, pager, next, total"
      :total="selectCategory.questions.length">
      </el-pagination>
    </div>
    <div v-if="showSave">
      <button type="button" class="btn btn-custom" v-on:click="savaAnswerToLocalFile()">保存到本地文件</button>
      <button type="button" class="btn btn-custom" v-on:click="savaAnswer()">保存并显示结果</button>
    </div>
  </div>
  <div class="pull-right width30 categoryBox">
    <div class="border padding10">
      <div>
        <label>问卷名称：</label>
        <span>{{questionnaireData.suName}}</span>
      </div>
      <div>
        <label>问卷描述：</label>
        <span>{{questionnaireData.description}}</span>
      </div>
      <div>
        <label>问题分类：</label>
      </div>
      <ul class="domtree">
        <li v-for="(item, key1) in surveyData.categorys">
          {{ item.name }}  
          <ul>
            <li class="pointer" v-for="(itemSon, key2) in item.children" v-on:click="changeCategory(key1, key2)">
              {{ itemSon.name }} 
              <label class="left10" 
              v-bind:class="{ 'red': itemSon.percent < 100, 'green': itemSon.percent == 100 }">
                完成： {{itemSon.percent}}%
              </label>
              <div class="progress">
                <div class="progress-bar"
                v-bind:class="{ 'bgRed': itemSon.percent < 100, 'bgGreen': itemSon.percent == 100 }"
                aria-valuemin="0" aria-valuemax="100"
                :aria-valuenow="itemSon.percent"
                :style=" 'width: '+ itemSon.percent +'%'">
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <div class="border padding10 top10" v-if="assessType === 'personnel'">
      <label>人员信息:</label>
      <p class="text-muted">姓名: {{ personnel.name }}</p>
      <p class="text-muted">身份证: {{ personnel.idNumber }}</p>
      <p class="text-muted">联系电话: {{ personnel.phone }}</p>
      <p class="text-muted">民族: <span> {{ personnel.nationality }}</span></p>
      <p class="text-muted">性别: <span> {{ personnel.sex }}</span></p>
      <p class="text-muted">出生日期：{{ personnel.birthday }}</p>
      <p class="text-muted">年龄: <span> {{ personnel.age }}</span></p>
      <p class="text-muted">身高: <span> {{ personnel.height }}</span></p>
      <p class="text-muted">体重: <span> {{ personnel.weight }}</span></p>
      <p class="text-muted">职业:<span> {{ personnel.occupation }}</span></p>

      <p class="text-muted">文化程度: <span> {{ $store.getters.getDictionary.education[personnel.education] }}</span></p>
      <p class="text-muted">婚姻状况: <span> {{ $store.getters.getDictionary.maritalStatus[personnel.maritalStatus] }}</span></p>
      <p class="text-muted">经济来源: <span> {{ $store.getters.getDictionary.incomeSource[personnel.incomeSource] }}</span></p>
      <p class="text-muted">收入水平: <span> {{ $store.getters.getDictionary.incomeLevel[personnel.incomeLevel] }}</span></p>
      <p class="text-muted">日常生活支出: <span> {{ $store.getters.getDictionary.dailyExpenses[personnel.dailyExpenses] }}</span></p>
      <p class="text-muted">常住居所: <span> {{ $store.getters.getDictionary.residenceType[personnel.residenceType] }}</span></p>
      <p class="text-muted">长期居住状态: <span> {{ $store.getters.getDictionary.residentialStatus[personnel.residentialStatus] }}</span></p>
      <p class="text-muted">备注: <span> {{ personnel.description }}</span></p>
    </div>
    <div class="border padding10 top10" v-if="assessType === 'institution'">
      <label>机构信息:</label>
      <p class="text-muted">机构名称: {{ personnel.name }}</p>
      <p class="text-muted">备注: <span> {{ personnel.description }}</span></p>
    </div>
  </div>
</div>
</template>
<script>
import saveFile from '../../js/saveTextFile.js'

import questionsComp from './answerQuestion.vue'

export default {
  name: 'answerQuestionnaire',
  data () {
    return {
      selectCategory: {},
      selectCategoryIndex: {
        parentIndex: null,
        index: null
      },
      surveyData: {},
      answerData: {},
      answerQuestions: {},
      showSave: false,
      saveUrl: '',
      // 问题分页
      page: 1,
      pageSize: 2,
      showQuestions: []
    }
  },
  props: {
    assessType: {
      // institution: 机构评估, personnel: 人员健康评估
      type: String,
      default: ''
    },
    personnel: {
      type: Object,
      default: {}
    },
    questionnaireData: {
      type: Object,
      default: {}
    }
  },
  components: {
    questionsComp
  },
  methods: {
    // 离线数据操作
    addLocalStorage () {
      if (typeof(Storage) !== "undefined") {
        let storageData ={
          personnel: this.personnel,
          questionnaireData: this.questionnaireData,
          saveUrl: this.saveUrl,
          answerData: this.answerData,
          surveyData: this.surveyData,
          selectCategoryIndex: this.selectCategoryIndex,
          // selectCategory: this.selectCategory
        }
        localStorage.setItem("currentAssessment", JSON.stringify(storageData))
      } else {
        alert('你的浏览器不支持Web Storage，无法使用离线功能')
      }
    },
    modifyLocalStorage () {
      let storageData = JSON.parse(localStorage.getItem("currentAssessment"))
      storageData.saveUrl = this.saveUrl
      storageData.surveyData = this.surveyData
      storageData.selectCategoryIndex = this.selectCategoryIndex
      // storageData.selectCategory = this.selectCategory
      localStorage.setItem("currentAssessment", JSON.stringify(storageData))
    },
    clearLocalStorage () {
      localStorage.removeItem('currentAssessment')
      // localStorage.clear()
    },
    initData (obj) {
      if (localStorage.getItem("currentAssessment")) {
        // 用保存的未完成数据初始化
        let storageData =  JSON.parse(localStorage.getItem("currentAssessment"))
        // this.personnel = storageData.personnel
        // this.questionnaireData = storageData.questionnaireData
        this.saveUrl = storageData.saveUrl
        this.answerData = storageData.answerData
        this.surveyData = storageData.surveyData
        this.changeCategory(storageData.selectCategoryIndex.parentIndex, storageData.selectCategoryIndex.index)
        this.chackComplete()
      }
      else {
        // 用新数据初始化
        if (this.assessType === 'institution') {
          this.answerData.assessType = 'institution'
          this.answerData.organizationId = this.personnel.id   // 被评测机构
          this.answerData.appraiserId = this.$store.getters.getUserData.id
          this.saveUrl = 'insAssessment/saveInsAssessment'
        } else if (this.assessType === 'personnel') {
          this.answerData.assessType === 'personnel'
          this.answerData.personnelId = this.personnel.id   // 被评测人员Id
          this.answerData.organizationId = this.$store.getters.getUserData.organizationId
          this.answerData.appraiserId = this.$store.getters.getUserData.id
          this.saveUrl = 'surveyAnswer/save'
        }
        this.answerData.surveyId = this.questionnaireData.id    // 问卷Id
        this.answerData.surveyName = this.questionnaireData.suName
        this.answerData.questions = []
        this.answerData.dateTime = Date.parse(new Date())
        obj.categorys.map(
          (category) => {
            category.percent = 0
            category.children.map(
              (children) =>{
                children.percent = 0
                children.questions.map(
                  (question) => {
                    question.answerId = null
                    if (question.otherOptions && question.otherOptions.length > 0 && typeof(question.otherOptions) === 'string') {
                      question.otherOptions = JSON.parse(question.otherOptions)
                    }
                    // question.answerOptionScore = 0
                  }
                )
              }
            )
          }
        )
        this.surveyData = obj
        // 保存数据到浏览器，离线使用
        this.addLocalStorage()
        // 默认显示分类
        if (this.surveyData.categoryOrder && this.surveyData.categoryOrder.length > 0) {
          // 自定义排序显示
          let nextCategoryId = this.surveyData.categoryOrder[0]
          // 查找分类的位置
          this.surveyData.categorys.map(
            (primaryCategory, index1) => {
              this.surveyData.categorys[index1].children.map(
                (secondCategory, index2) => {
                  if (secondCategory.id === nextCategoryId) {
                    this.changeCategory(index1, index2)
                  }
                }
              )
            }
          )
        } else {
          this.changeCategory(0, 0)
        }
      }
    },
    destroyData () {
      this.answerQuestions = {}
      this.answerData = {}
      this.selectCategory = {}
      this.selectCategoryIndex.parentIndex = null
      this.selectCategoryIndex.index = null
      this.surveyData = {}
      this.clearLocalStorage()
      this.showSave = false
    },
    changeCategory (index1,index2) {
      this.selectCategoryIndex.parentIndex = index1
      this.selectCategoryIndex.index = index2
      this.selectCategory = this.surveyData.categorys[index1].children[index2]
      $('#assessmentDialog').scrollTop = 0
      this.modifyLocalStorage()
      this.handleCurrentChange(1)
    },
    // 分页显示问题
    handleCurrentChange (val) {
/*
      for (let index = 0; index < this.showQuestions.length; index++){
        if(!this.showQuestions[index].answerId){
          alert('未完成当前页，不能翻页！')
          return false
        }
      }
*/
      this.showQuestions = []
      this.page = val
      let i = (val - 1) * this.pageSize
      for(i; i < (val * this.pageSize); i++){
        if(i >= this.selectCategory.questions.length){
          return false
        }
        this.showQuestions.push(this.selectCategory.questions[i])
      }
      $('#questionsBox')
        .addClass('animated zoomIn')
        .one(
          'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
          function(){ 
            $(this).removeClass('animated zoomIn')
          }
        )
    },
    // 根据完成条件改变当前显示分类
    nextCategory () {
       // 未做完当前分类下的问题
      if (this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].percent < 100) {
        return false
      }
      if (this.surveyData.categoryOrder && this.surveyData.categoryOrder.length > 0) {
        // 奇葩变态的做题顺序跳转方案
        let categoryId = this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].id
        let nextIndex = null
        if (this.surveyData.categoryOrder.indexOf(categoryId) >= 0) {
          nextIndex = this.surveyData.categoryOrder.indexOf(categoryId) + 1
        } else {
          return false
        }
        if (!nextIndex || nextIndex === this.surveyData.categoryOrder.length) {
          return false
        }
        let nextCategoryId = this.surveyData.categoryOrder[nextIndex]
        //  查找下一个分类的位置并跳转
        this.surveyData.categorys.map(
          (primaryCategory, index1) => {
            this.surveyData.categorys[index1].children.map(
              (secondCategory, index2) => {
                if (secondCategory.id === nextCategoryId) {
                  this.changeCategory(index1, index2)
                }
              }
            )
          }
        )
      }
      else {
        // 已是最后一个分类
        if (this.selectCategoryIndex.parentIndex === (this.surveyData.categorys.length - 1) && this.surveyData.categorys[this.selectCategoryIndex.parentIndex].percent == 100) {
          return true
        }

        // 当前分类下的问题已做完
        if (this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].percent == 100) {
          // 已完成当前分类所属的一级分类所有问题
          if (this.surveyData.categorys[this.selectCategoryIndex.parentIndex].percent == 100) {
            this.changeCategory(this.selectCategoryIndex.parentIndex + 1, 0)
          }
          // 完成当前分类，但未完成当前分类所属一级分类
          else {
            if (this.selectCategoryIndex.index +1 >= this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children.length) {
              return false
            }
            this.changeCategory(this.selectCategoryIndex.parentIndex, this.selectCategoryIndex.index + 1)
          }
        }
      }
    },
    // 检查是否显示保存按钮
    chackComplete () {
      for (let key in this.surveyData.categorys) {
        if (!this.surveyData.categorys[key].percent || this.surveyData.categorys[key].percent < 100) {
          return
        }
      }
      this.answerData.dateTime = Date.parse(new Date())
      this.showSave = true
    },
    answerQuestion (index, questionData, radioData) {
      let num = 0
      for (let key in this.selectCategory.questions) {
        if (key == index) {
          this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].questions[key].answerId = radioData.id
          this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].questions[key].answer = radioData.optionName
          this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].questions[key].answerOptionScore = radioData.optionScore
        }
        if (this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].questions[key].answerId) {
          num ++
        }
      }
      // 计算当前分类完成百分百
      this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].percent
        = parseInt(num * 100 / this.selectCategory.questions.length)

      // 统计当前分类所属一级分类完成百分比
      let  percent = 0
      for (let key1 in this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children) {
        percent += (this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[key1].percent ? 
                this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[key1].percent : 0)
      }
      this.surveyData.categorys[this.selectCategoryIndex.parentIndex].percent = 
        parseInt(percent / this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children.length)

      // 保存离线使用数据
      this.modifyLocalStorage()

      // 检查是否显示保存按钮
      this.chackComplete()

      // 页面无刷新处理
      this.surveyData.categorys.push({})
      this.surveyData.categorys.splice(this.surveyData.categorys.length - 1, 1)

      // 根据完成条件改变当前显示分类
      this.nextCategory()
    },
    answerQuestionOther (questionIndex, otherOptions) {
      this.surveyData.categorys[this.selectCategoryIndex.parentIndex].children[this.selectCategoryIndex.index].questions[questionIndex].otherOptions = otherOptions
      // 保存离线使用数据
      this.modifyLocalStorage()
    },
    setAnswerQuestions () {
      this.answerQuestions = []
      for (let key1 in this.surveyData.categorys) {
        for (let key2 in this.surveyData.categorys[key1].children) {
          if (!this.surveyData.categorys[key1].children[key2].percent || this.surveyData.categorys[key1].children[key2].percent < 100) {
            alert('有部分问题还未回答')
            return false
          }
          for (let key3 in this.surveyData.categorys[key1].children[key2].questions) {
            if (this.surveyData.categorys[key1].children[key2].questions[key3].answerId) {
              let _otherOptionsAnswer = []
              // 组装附加选项回答结果
              for (let index in this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions) {
                if (!this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions[index].answerValue) {
                  continue
                }
                let answer = this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions[index].question + ': '
                // 多选
                if (typeof(this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions[index].answerValue)==='object') {
                  answer += this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions[index].answerValue.join(';')
                }
                // 单选或文字回答
                else {
                  answer += this.surveyData.categorys[key1].children[key2].questions[key3].otherOptions[index].answerValue
                }
                _otherOptionsAnswer.push(answer)
              }
              this.answerQuestions.push(
                {
                  primaryCategoryId: this.surveyData.categorys[key1].id,
                  secondCategoryId: this.surveyData.categorys[key1].children[key2].id,
                  questionId: this.surveyData.categorys[key1].children[key2].questions[key3].id,
                  questionName: this.surveyData.categorys[key1].children[key2].questions[key3].quName,
                  questionItem: this.surveyData.categorys[key1].children[key2].questions[key3].item,
                  optionId: this.surveyData.categorys[key1].children[key2].questions[key3].answerId,
                  optionAnswer: this.surveyData.categorys[key1].children[key2].questions[key3].answer,
                  optionScore: this.surveyData.categorys[key1].children[key2].questions[key3].answerOptionScore,
                  otherOptionsAnswer: _otherOptionsAnswer
                }
              )
            }
          }
        }
      }
      return true
    },
    savaAnswer () {
      if (!this.setAnswerQuestions()){
        return false
      }
      this.answerData.questions = this.answerQuestions
      this.$alert('正在分析...', '', true)
      this.$http.post(this.saveUrl, this.answerData).then(
        response => {
          // alert(response.data.message)
          this.destroyData()
          this.$alert('', '', false)
          this.$emit('showAssessmentResult', response.data.data)
        }
      )
    },
    savaAnswerToLocalFile () {
      if (!this.setAnswerQuestions()){
        return false
      }
      this.answerData.questions = this.answerQuestions
      let blob = new Blob([JSON.stringify(this.answerData)], {type: 'application/json;charset=utf-8'});
      if (this.assessType === 'institution') {
        saveFile(blob, this.personnel.name + '.json')
      } else if (this.assessType === 'personnel') {
        saveFile(blob, this.personnel.name  + this.personnel.idNumber + '.json')
      }
    }
  },
  created () {
    this.initData(this.questionnaireData)
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
p{margin: 0; line-height: 180%;}
.progress {
    height: 2px;
    margin-bottom: 0px;
}
.progress-bar {
}
.bg-select{background: #ecf0f5;}
.questionsBox{
  min-height: 490px;
}
.categoryBox{
  height: 550px;
  overflow-y: scroll;
}
</style>
